package com.bdqn.business.academic.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.business.academic.dao.BooksMapper;
import com.bdqn.business.academic.dao.ChapterMapper;
import com.bdqn.entity.academic.Books;
import com.bdqn.entity.academic.Chapter;
import com.bdqn.response.PageResult;
import com.bdqn.response.Result;
import com.bdqn.response.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
@Transactional
public class ChapterService {

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private BooksMapper booksMapper;

    public Result getList(Map<String, Object> map) {
        IPage<Chapter> iPage = new Page<>(Integer.parseInt(map.get("page").toString()),Integer.parseInt(map.get("size").toString()));
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("books_id");
        queryWrapper.orderByDesc("sort_number");
        IPage<Chapter> result = chapterMapper.selectPage(iPage, queryWrapper);
        return new Result(ResultCode.SUCCESS,new PageResult<Chapter>(result.getTotal(),result.getRecords()));
    }

    @CachePut(cacheNames = "chapter",key = "#chapter.id")
    public Result save(Chapter chapter) {
        Books books = booksMapper.selectById(chapter.getBooksId());
        chapter.setBooksName(books.getName());
        chapterMapper.insert(chapter);
        return new Result(ResultCode.SUCCESS,chapter);
    }
}
